package demo.action;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import demo.entity.Follow;
import demo.entity.User;
import demo.service.FollowService;
import demo.service.UserService;
import demo.util.ImageCrop;
import demo.util.MD5;
import freemarker.template.Template;
import freemarker.template.TemplateException;

@SuppressWarnings("serial")
public class UserAction extends BaseAction {

	private User user;
	private UserService userService;
	private FollowService followService;
	private String validcode;
	private int userid;
	private String search;
	private String result;
	private JavaMailSender javaMailSender;	
	private FreeMarkerConfig freeMarkerConfig;
	
	private File avatar;
	private String avatarFileName;
	private String avatarContentType;
	private static final String PATH_UPLOAD_AVATAR = "/upload_avatar";
	
	private int x;
	private int y;
	private int w;
	private int h;
	private String f;
	
	private int id;
	private String domain;
	
	
	private final static String HQL_LOGIN = "from User where email=:email and password=:password";
	private final static String HQL_SEARCH_USER = "from User where nick like :search ";
	private final static String HQL_ALL_FOLLOWED = "from Follow as f where f.userid=:userid";
	private static final String FROM = "weibodotcom@126.com";
	
//	private Vector<Integer> vi = new Vector<Integer>();
	
	public String register() throws Exception {
		String validcode_session = (String) getSession().get(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		if (validcode.equalsIgnoreCase(validcode_session)) {
			user.setPassword(MD5.encrypt(user.getPassword()));
			//用户注册成功，但未激活
			String rand = MD5.encrypt(user.getEmail()+"abc");
			user.setActive(rand);
			user.setAvatar("default.gif");
			userService.save(user);
			//发送激活邮件
			sendEmail(user.getEmail(), rand);
			return SUCCESS;
		} else {
			getRequest().put("message_error", "验证码错误");
			return INPUT;
		}
	}
	
	public String login() throws Exception {
		String[] paramNames = {"email", "password"};
		String[] values = {this.user.getEmail(), MD5.encrypt(this.user.getPassword())};
		//login
//		User user = userService.login(HQL_LOGIN, values);
//		if (user != null) {
//			getSession().put("user", user);
//			return SUCCESS;
//		} else {
//			return INPUT;
//		}
		//queryByNameParam
		List<User> list = userService.queryByNameParam(HQL_LOGIN, paramNames, values);
		if (list.size() == 0) {
			getRequest().put("message_error", "用户名/密码错误");
			return INPUT;
		} else {
			User user = list.get(0);
			getSession().put("user", user);
			setUser(user);
//			this.setUserid(user.getId());
			return SUCCESS;
		}
	}
	
	public String home() throws Exception {
		System.out.println("in UserAction home...");
		System.out.println("id:" + id);
		System.out.println("domain" + domain);
		
//		HttpServletRequest request = ServletActionContext.getRequest();
		if (id!=0) {
			return "id";
		} else if(domain!=null) {
			return "domain";
		} else {
			return ERROR;
		}
	}
	
	public String search() throws Exception {

		String[] paramNames = {"search"};
		String[] values = {"%"+search+"%"};
		List<User> list = userService.queryByNameParam(HQL_SEARCH_USER, paramNames, values);
		List<Map<String, Object>> maps = new ArrayList<Map<String,Object>>();
		for (User user : list) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", user.getId());
			map.put("nick", user.getNick());
			map.put("avatar", user.getAvatar());
			map.put("sex", user.getSex());
			map.put("province", user.getProvince());
			map.put("county", user.getCounty());
			map.put("isfollowed", isFollowed(user.getId()));
			maps.add(map);
		}
//System.out.println("vi:");
//for (Integer integer : vi) {
//	System.out.println(integer + ",");
//}	
		//URL转码
//		setSearch(URLEncoder.encode(this.search, "UTF-8"));
		JSONArray jsonArray = JSONArray.fromObject(maps);
		setResult(jsonArray.toString());
System.out.println(result);
		return SUCCESS;
	}
	
	private boolean isFollowed(int userid) {//判断参数userid是否是当前user已经关注的
		User user = (User) getSession().get("user");
		String[] paramNames = {"userid"};
		Integer[] values = {user.getId()};
		List<Follow> list = followService.queryByNameParam(HQL_ALL_FOLLOWED, paramNames, values);
		for (Follow follow : list) {
			int followid = follow.getFollowid();
//vi.add(followid);
			if (userid == followid) {
				return true;
			}
		}
		return false;
	}
	
	public String upload() throws Exception {
		System.out.println("upload...");
		
		System.out.println(avatar);
		System.out.println(avatarFileName);
		System.out.println(avatarContentType);
		
		//上传文件保存路径
		String savePath = ServletActionContext.getServletContext().getRealPath(PATH_UPLOAD_AVATAR);
		String fileName = Long.toString(System.nanoTime());
		String fileExtension = avatarFileName.substring(avatarFileName.lastIndexOf('.'));
		avatar.renameTo(new File(savePath + "/" + fileName + fileExtension));//renameTo实现

		HttpServletResponse response = ServletActionContext.getResponse();   
		response.setCharacterEncoding("utf-8"); 
		
		Map<String, String> map = new HashMap<String, String>();
		map.put("newname", fileName+fileExtension);
		JSONObject jsonObject = JSONObject.fromObject(map);
		response.getWriter().print(jsonObject);
		return null;
	}
	
	public String crop() throws Exception {
		System.out.println("crop...");
		String savePath = ServletActionContext.getServletContext().getRealPath(PATH_UPLOAD_AVATAR);
		String newavtar = ImageCrop.doCrop(x, y, w, h, savePath+"/"+f);

//		取得user
		User user = (User) getSession().get("user");

//		更新数据库avatar字段
		user.setAvatar(newavtar);
		userService.update(user);

//		重设session中user的avatar值
		getSession().put("user", user);
		
//		返回result：success
		Map<String, String> map = new HashMap<String, String>();
		map.put("result", "success");
		JSONObject jsonObject = JSONObject.fromObject(map);
		setResult(jsonObject.toString());
		return SUCCESS;
	}
	
	private void sendEmail(String to, String rand) {
		MimeMessage mimeMessage = javaMailSender.createMimeMessage();
		MimeMessageHelper mimeMessageHelper;
		try {
			mimeMessageHelper = new MimeMessageHelper(mimeMessage, false, "utf-8");
			mimeMessageHelper.setFrom(FROM);
			mimeMessageHelper.setTo(to);
			mimeMessageHelper.setSubject("微博开通确认");
			String text = "";
			
			Map<String, String> map = new HashMap<String, String>();
			map.put("email", to);
			map.put("rand", rand);
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			map.put("date", simpleDateFormat.format(new Date()));
			
			//加载模板文件
			try {
				Template template = freeMarkerConfig.getConfiguration().getTemplate("active.ftl");
				text = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
			} catch (IOException e) {
				e.printStackTrace();
			} catch (TemplateException e) {
				e.printStackTrace();
			}
			
			mimeMessageHelper.setText(text, true);
			
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		javaMailSender.send(mimeMessage);//
	}
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void setFollowService(FollowService followService) {
		this.followService = followService;
	}

	public String getValidcode() {
		return validcode;
	}

	public void setValidcode(String validcode) {
		this.validcode = validcode;
	}

	public int getUserid() {
		return userid;
	}

	public void setUserid(int userid) {
		this.userid = userid;
	}

	public String getSearch() {
		return search;
	}

	public void setSearch(String search) {
		this.search = search;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public void setJavaMailSender(JavaMailSender javaMailSender) {
		this.javaMailSender = javaMailSender;
	}

	public void setAvatar(File avatar) {
		this.avatar = avatar;
	}

	public void setAvatarFileName(String avatarFileName) {
		this.avatarFileName = avatarFileName;
	}

	public void setAvatarContentType(String avatarContentType) {
		this.avatarContentType = avatarContentType;
	}

	public void setX(int x) {
		this.x = x;
	}

	public void setY(int y) {
		this.y = y;
	}

	public void setW(int w) {
		this.w = w;
	}

	public void setH(int h) {
		this.h = h;
	}

	public void setF(String f) {
		this.f = f;
	}

	public void setFreeMarkerConfig(FreeMarkerConfig freeMarkerConfig) {
		this.freeMarkerConfig = freeMarkerConfig;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getDomain() {
		return domain;
	}

	public void setDomain(String domain) {
		this.domain = domain;
	}
	
}
